﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

using LowLevelGraphics.Histograms;

using LowLevelGraphics.Extractors;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Entropy Map
    /// </summary>
    public class EntropyMap : BaseImageFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EnergyMap"/> class.
        /// </summary>
        public EntropyMap()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EnergyMap"/> class.
        /// </summary>
        /// <param name="_energyMap">The _energy map.</param>
        internal EntropyMap(EntropyMap _energyMap)
        {
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;
            //            histogram.SortBy(PROCESSING_MODE.GrayColor);

            int y=0;
            int x=0;

            int nWidth = _bitmap.Width;
            int nHeight = _bitmap.Height;

            int[] aCountGrayValue = new int[256];

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    int nGray = _bitmap.GetGrayPixelValue(x,y);
                    aCountGrayValue[nGray]++;
                }
            }

            int nEntropy = 0;
            int i=0;
            for (i = 0; i < 256; i++)
            {
                nEntropy += (int)(aCountGrayValue[i]*Math.Log10(aCountGrayValue[i]));
            }
            nEntropy = -nEntropy;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    int nGray = _bitmap.GetGrayPixelValue(x,y);
                    int nColor = aCountGrayValue[nGray];
                    int newVariable = (int)(nColor * Math.Log(nColor));
                    Color color = Color.FromArgb(newVariable*newVariable);
                    _bitmap.SetPixel(x, y, ColorFunctions.GrayColor(color));
                }
            }      
            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new EntropyMap(this);
        }
    }
}
